﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class ModuleReferenceRule : ILRule<ModuleReferenceHandle>
    {
        [ILInfo(true)]
        public string ModuleName { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public ModuleReferenceRule(
            string moduleName)
            : base()
        {
            ModuleName = moduleName;
        }

        public ModuleReferenceRule(MetadataReader reader, ModuleReferenceHandle moduleReferenceHandle)
            : base(reader)
        {
            ModuleReference moduleReference = reader.GetModuleReference(moduleReferenceHandle);
            ModuleName = reader.GetString(moduleReference.Name);
            CustomAttributes = moduleReference.GetCustomAttributes();
        }

        public override ModuleReferenceHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddModuleReference(
                moduleName: ModuleName == null ? default : builder.GetOrAddString(ModuleName));
        }
    }
}